//
//  HSDFUViewController.m
//  HbandSDk_Example
//
//  Created by LRB_C on 2020/8/21.
//  Copyright © 2020 18675079557@163.com. All rights reserved.
//

#import "HSDFUViewController.h"
@import iOSDFULibrary;

@interface HSDFUViewController ()<DFUServiceDelegate,DFUProgressDelegate,EGMBleHandlerDelagate>
@property (nonatomic,strong) NSURL *selectedFileURL;
@property(nonatomic, strong) DFUServiceController *dfuController;

@property (weak, nonatomic) IBOutlet UILabel *dfuStatusLabel;
@property (nonatomic,assign) BOOL isUploadIng;
@property (weak, nonatomic) IBOutlet UILabel *versionlabel;
@property (nonatomic,strong) CBPeripheral *curenntDevice;
@property (nonatomic,assign) BOOL isEnterDFU;
@end

@implementation HSDFUViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     _dfuStatusLabel.text = @"设备升级后会进行重启，请重新连接。如果连接不成功，请在手机蓝牙设置中忽略设备后重新扫描连接。固件升级后，心率血压体温等数据会被抹掉，请在此之前做好缓存。";
    _curenntDevice = [EGMBleHandler sharedBleHandler].bleManager.discoveredPeripheral;
    [EGMBleHandler sharedBleHandler].delegate = self;
    
}

//DFU逻辑 ：调用writeCmdOfEnterDFU后蓝牙进入dfu模式，自动断开连接，需要重新扫描连接dfu模式的设备。以DFU_开头的设备
// 断开…进入dfu模式…连接…发文件…重启
- (IBAction)startAction:(UIButton *)sender {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"5.6.54" ofType:@"zip"];
    self.selectedFileURL = [NSURL URLWithString:path];
    [self startDFU];
}

-(void)startDFU{
    
    if (!self.selectedFileURL) {
        _dfuStatusLabel.text = @"请选择固件版本";
        return;
    }
    //判断蓝牙状态
    if (![EGMBleHandler sharedBleHandler].deviceIsConnected) {
        _dfuStatusLabel.text = @"蓝牙未连接";
        return;
    }
    
    if (_isUploadIng) {
        _dfuStatusLabel.text = @"正在升级，请勿操作";
               return;
    }
    
    if ([_curenntDevice.name containsString:@"DFU_"]) { //连接的是dfu模式的设备
        _isEnterDFU = YES;
        [self startSecureDFU];
    }else{
        [[EGMBleHandler sharedBleHandler].operClient.setInfoOperation writeCmdOfEnterDFU];//写入指令后蓝牙会断开，handleMsgDisconnected回调
        _isEnterDFU = YES;
    }
   
}

-(void)scanDFUDevice{
    _dfuStatusLabel.text = @"扫描DFU模式设备";
    [[EGMBleHandler sharedBleHandler] scanBLeDeviceWtihBlock:^(NSArray<CBPeripheral *> *peripherals) {
        for (CBPeripheral *device in peripherals) {
            if ([device.name containsString:@"DFU_"]) { //可以进一步进行比对
                 _dfuStatusLabel.text = @"连接DFU模式设备";
               [[EGMBleHandler sharedBleHandler] connectPeripheral:device conectBlok:nil]; //连接成功后handleMsgConnected中回调，此处不用block回调，block主要用于连接成功切配对后
                break;
            }
        }
    }];
}

-(void)startSecureDFU{
      _dfuStatusLabel.text = @"开始升级";
    CBPeripheral *discoveredPeripheral = [EGMBleHandler sharedBleHandler].bleManager.discoveredPeripheral;
    DFUServiceInitiator *initiator = [[DFUServiceInitiator alloc] initWithQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    initiator.delegate = self;
    initiator.progressDelegate = self;
    DFUFirmware *selectedFirmware = [[DFUFirmware alloc] initWithUrlToZipFile:self.selectedFileURL];
    self.dfuController = [[initiator withFirmware:selectedFirmware] startWithTarget:discoveredPeripheral];
}

#pragma mark - Handle Delegate

//代理 蓝牙断开连接调用， 进入dfu模式后设备会断开连接 需要重新扫描dfu模式下的设备并连接才可以进行下一步升级
-(void)handleMsgDisconnected{
      _dfuStatusLabel.text = @"蓝牙断开连接";
    if (self.isEnterDFU) { //扫描进入dfu的设备
      
        [self scanDFUDevice];
    }
}

//代理 蓝牙连接成功。
-(void)handleMsgConnected{
      
    if (self.isEnterDFU) { //扫描进入dfu的设备
         _dfuStatusLabel.text = @"DFU模式蓝牙设备连接成功";
        [self startSecureDFU];
    }else{
          _dfuStatusLabel.text = @"普通模式蓝牙设备连接成功";
    }
}



//MARK: - DFUServiceDelegate
-(void)dfuStateDidChangeTo:(enum DFUState)state{
    switch(state) {
    case DFUStateConnecting: //连接
            _dfuStatusLabel.text = @"正在连接";
            break;
    case DFUStateStarting: //开始
         _dfuStatusLabel.text = @"开始升级";
            break;
    case DFUStateEnablingDfuMode://允许dfu
        _dfuStatusLabel.text = @"允许dfu";
            break;
    case DFUStateUploading://正在上传固件
        _dfuStatusLabel.text = @"正在上传固件";
        _isUploadIng = YES;
            break;
    case DFUStateValidating://验证
         _dfuStatusLabel.text = @"正在验证";
            break;
    case DFUStateDisconnecting://断开连接
            _dfuStatusLabel.text = @"断开连接";
            _isEnterDFU = NO;
             _isUploadIng = NO;
            break;
    case DFUStateCompleted://完成
            _dfuStatusLabel.text = @"升级完成,10s后重新连接设备";
            _isUploadIng = NO;
            _isEnterDFU = NO;
            [self performSelector:@selector(upgradeComplete) withObject:nil afterDelay:10];
            break;
    case DFUStateAborted://失败
          _dfuStatusLabel.text = @"升级失败";
            _isEnterDFU = NO;
            _isUploadIng = NO;
            break;
    }
}

//失败回调 可进行重试 延迟两秒后startSecureDFU 逻辑自行定义
-(void)dfuError:(enum DFUError)error didOccurWithMessage:(NSString *)message{
    _dfuStatusLabel.text = [NSString stringWithFormat:@"升级失败,错误编码:%ld,原因:%@",error,message];
}

//MARK: - DFUProgressDelegate

//升级进度
-(void)dfuProgressDidChangeFor:(NSInteger)part outOf:(NSInteger)totalParts to:(NSInteger)progress currentSpeedBytesPerSecond:(double)currentSpeedBytesPerSecond avgSpeedBytesPerSecond:(double)avgSpeedBytesPerSecond{
    NSString *text = _dfuStatusLabel.text;
    if (!text) text = @"";
    text = [NSString stringWithFormat:@"上传固件 当前进度:%ld %",progress];
    _dfuStatusLabel.text = text;
   
}

#pragma mark - 升级完成

//升级完成后 重新扫描不是dfu的设备
-(void)upgradeComplete{

    [[EGMBleHandler sharedBleHandler] disConnectCurretPeripheral];
    _dfuStatusLabel.text = @"重新扫描设备进行连接";

 
    [[EGMBleHandler sharedBleHandler] tryToScanAndConnectPeripheralWIthNSUUIDStr:[_curenntDevice.identifier UUIDString] conectBlok:^(BOOL isConnect) {
             NSLog(@"连接缓存设备%@",isConnect?@"成功":@"失败");
            
        [self readdeviceInfo];
        }];
}

-(void)readdeviceInfo{
   _dfuStatusLabel.text = @"同步当天计步和设备信息数据:";
      [[EGMBleHandler sharedBleHandler].operClient.infoOperation enableReadDeviceNotify:YES];
        [[EGMBleHandler sharedBleHandler].operClient.infoOperation readDeviceCurrenInfoData];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceInfo:) name:NOTIFICATION_DEVICEINFO_DATA_UPDATED object:nil];
    
}

-(void)handleDeviceInfo:(NSNotification*)noti{
  
    BLeDeviceInfoModel *info = [noti.userInfo objectForKey:KEY_NOTIFICATION_USER_INFO];
    _dfuStatusLabel.text = [NSString stringWithFormat:@"设备信息同步结果(请晃动手环，可以实时更新数据)：%@",[info lrbDescription]];
}
@end
